# coding=UTF-8

from amscms.ams.managers import AdLikeManager, AdManager, AdTagManager, \
    AdViewManager, AdStatsManager, AdTagExploreHistoryManager, \
    AdSearchHistoryManager, AdOrderManager, AdvertizerManager, AdPricingManager
from amscms.dict.models import Term
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext as _

ADVERTIZER_TYPES = (
    (u'Individual', _("Individual")),
    (u'Company', _("Company"))
)

'''
Advertizer 

@author: Behrooz Nobakht
'''
class Advertizer(models.Model):
    id = models.AutoField(primary_key=True, verbose_name=_("Id"))
    user = models.ForeignKey(User)
    type = models.CharField(max_length=32, choices=ADVERTIZER_TYPES, verbose_name=_("Type"))
    description = models.TextField(verbose_name=_("Description"))
    objects = AdvertizerManager()
    
    def __unicode__(self):
        return _(self.type) + " - " + self.user.get_full_name()
    
    class Meta:
        db_table = "ams_advertizer"
        verbose_name = _("Advertizer")
        verbose_name_plural = _("Advertizers")

"""
Ad Model Class
@author: Behrooz Nobakht
"""
class Ad(models.Model):
    id = models.AutoField(primary_key=True, verbose_name=_("Id"))
    advertizer = models.ForeignKey(Advertizer)
    title = models.CharField(max_length=256, verbose_name=_("Title"))
    description = models.TextField(verbose_name=_("Description"))
    registration_date = models.DateField(verbose_name=_("Registration Date"), auto_now_add=True)
    start_date = models.DateField(verbose_name=_("Publish Start Date"))
    end_date = models.DateField(verbose_name=_("Publish End Date"))
    url = models.URLField(verbose_name=_("URL Address"), null=True, blank=True)
    enabled = models.BooleanField(verbose_name=_("Enabled"), default=False)
    stats = models.OneToOneField('AdStats', related_name='the_ad', null=True, blank=True)
    objects = AdManager()
    
    def __unicode__(self):
        return self.title
    
    def save_tags(self, tags):
        if len(tags) == 0:
            return True
        for tag_term in tags:
            tag_term = tag_term.strip()
            if tag_term == "":
                continue
            try:
                the_term = Term.objects.find_or_create(tag_term)
                if the_term is None:
                    return False
                the_term.frequency = the_term.frequency + 1
                AdTag.objects.save_or_update(self, the_term)
                the_term.save()
            except Exception:
                return False
        return True
    
    def delete(self, *args, **kwargs):
        adtags = AdTag.objects.all().filter(ad=self)
        for at in adtags:
            term = at.term
            term.frequency = term.frequency - 1
            term.save()
        super(Ad, self).delete(*args, **kwargs)
    
    class Meta:
        db_table = 'ams_ad'
        ordering = ["-start_date"]
        verbose_name = _("Ad")
        verbose_name_plural = _("Ads")

"""
Ad Tag 

@author: Behrooz Nobakht
"""
class AdTag(models.Model):
    id = models.AutoField(primary_key=True, verbose_name=_("Id"))
    last_modified = models.DateTimeField(verbose_name=_("Last Modified"), auto_now=True)
    ad = models.ForeignKey(Ad)
    term = models.ForeignKey(Term)
    objects = AdTagManager()
    class Meta:
        db_table = "ams_adtag"
        verbose_name = _("Ad Tag")
        verbose_name_plural = _("Ad Tags")


"""
Ad Like

@author: Behrooz Nobakht
"""
class AdLikeDislike(models.Model):
    id = models.AutoField(primary_key=True, verbose_name=_("Id"))
    ad = models.ForeignKey(Ad)
    user = models.ForeignKey(User)
    score = models.IntegerField(verbose_name=_("Score"))
    last_modified = models.DateTimeField(verbose_name=_("Last Modified"), auto_now=True)
    objects = AdLikeManager()
    class Meta:
        db_table = "hst_adlikedislike"
        verbose_name = _("Ad LikeDislike")
        verbose_name_plural = _("Ad LikeDislikes")

        
"""
@author: Behrooz Nobakht
"""        
class AdView(models.Model):
    id = models.AutoField(primary_key=True, verbose_name=_("Id"))
    ad = models.ForeignKey(Ad)
    user = models.ForeignKey(User, null=True)
    last_modified = models.DateTimeField(verbose_name=_("Last Modified"), auto_now_add=True)
    referer = models.CharField(max_length=256, verbose_name=_("Referer"), null=True)
    viewer_ip = models.IPAddressField(verbose_name=_("IP Address"), null=True)
    objects = AdViewManager()
    class Meta:
        unique_together = (("ad", "user", "last_modified"),)
        db_table = "hst_adview"
        verbose_name = _("Ad View History")
        verbose_name_plural = _("Ad View Histories")

"""
@author: Behrooz Nobakht
"""        
class AdStats(models.Model):
    id = models.AutoField(primary_key=True, verbose_name=_("Id"))
    ad = models.OneToOneField(Ad, related_name="the_stats")
    score = models.IntegerField(verbose_name=_("Score"))
    views = models.IntegerField(verbose_name=_("View Count"))
    likes = models.IntegerField(verbose_name=_("Like Count"))
    dislikes = models.IntegerField(verbose_name=_("Dislike Count"))
    last_modified = models.DateTimeField(verbose_name=_("Last Modified"), auto_now=True)
    objects = AdStatsManager()
    
    def update_score(self):
        self.score = self.views + 2 * self.likes - self.dislikes
        super(AdStats, self).save()
        return
    
    class Meta:
        db_table = "hst_adstats"
        verbose_name = _("Ad Stats")
        verbose_name_plural = _("Ad Stats")
    
"""
"""    
class AdSearchHistory(models.Model):
    id = models.AutoField(primary_key=True, verbose_name=_("Id"))
    user = models.ForeignKey(User, null=True)
    term = models.ForeignKey(Term)
    viewed_on = models.DateTimeField(verbose_name=_("Viewed On"))
    objects = AdSearchHistoryManager()
    class Meta:
        db_table = "hst_adsearch"
        verbose_name = _("Ad Search History")
        verbose_name_plural = _("Ad Search Histories")

        

"""
"""        
class AdTagExploreHistory(models.Model):
    id = models.AutoField(primary_key=True, verbose_name=_("Id"))
    user = models.ForeignKey(User, null=True)
    term = models.ForeignKey(Term)
    viewed_on = models.DateTimeField(verbose_name=_("Viewed On"))
    referer = models.CharField(max_length=256, verbose_name=_("Referer"), null=True)
    viewer_ip = models.IPAddressField(verbose_name=_("IP Adresss"), null=True)
    objects = AdTagExploreHistoryManager()
    class Meta:
        db_table = "hst_adtag_explr"
        verbose_name = _("Ad Explore History")
        verbose_name_plural = _("Ad Explore Histories")

        

"""
"""        
class AdOrder(models.Model):
    id = models.AutoField(primary_key=True, verbose_name=_("Id"))
    ad = models.ForeignKey(Ad)
    amount = models.FloatField(verbose_name=_("Amount"))
    paid = models.BooleanField(verbose_name=_("Paid"), default=False)
    payment_date = models.DateTimeField(verbose_name=_("Payment Date"), null=True)
    objects = AdOrderManager()
    class Meta:
        db_table = "ams_adorder"
        verbose_name = _("Ad Order")
        verbose_name_plural = _("Ad Orders")

class AdPricing(models.Model):
    id = models.AutoField(primary_key=True, verbose_name=_("Id"))
    enabled = models.BooleanField(default=False, verbose_name=_("Enabled"))
    is_default = models.BooleanField(default=False, verbose_name=_("Default"))
    daily_rate = models.FloatField(verbose_name=_("Daily Rate"))
    min_days_discount = models.PositiveIntegerField(null=True, blank=True, verbose_name=_("Minimum days to start discount"))
    min_days_discount_forevery = models.PositiveIntegerField(null=True, blank=True, verbose_name=_("For every number of days"))
    min_days_discount_rate = models.PositiveIntegerField(null=True, blank=True, verbose_name=_("Days Discount Rate"))
    range_discount_start = models.DateField(null=True, blank=True, verbose_name=_("Range Discount Start Date"))
    range_discount_end = models.DateField(null=True, blank=True, verbose_name=_("Range Discount End Date"))
    range_discount_forevery = models.PositiveIntegerField(null=True, blank=True, verbose_name=_("For every number of days"))
    range_discount_rate = models.PositiveIntegerField(null=True, blank=True, verbose_name=_("Range Discount Rate"))
    objects = AdPricingManager()
    class Meta:
        db_table = "ams_adpricing"
        verbose_name = _("Ad Pricing")
        verbose_name_plural = _("Ad Pricings")
    